package com.sjf.reggie.controller;

import com.sjf.common.CustomException;
import com.sjf.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传和下载
 *
 * @author <huangtang>
 * @since 2022/4/26 12:38
 **/
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {


    @Value("${reggie.filepath}")
    private String REGGIE_FILEPATH;

    /**
     * 文件下载
     * @param name
     * @return
     */
    @GetMapping("/download")
    public void download( String name, HttpServletResponse response ){
        try {
            //输入流接收文件内容
            FileInputStream fis = new FileInputStream (new File (REGGIE_FILEPATH + name));
            //输出流将图片输出到浏览器端进行展示
            ServletOutputStream oos = response.getOutputStream ();
            response.setContentType ("image/jpg");
            int len = 0;
            byte[] bytes = new byte[1024];
            //将输入流的数据读取到缓冲区中
            while( (len = fis.read (bytes)) != -1){
                //将缓冲区的数据读取到输出流中
                oos.write (bytes,0,len);
                oos.flush ();
            }

            fis.close ();
            oos.close ();
        } catch (Exception e) {
            System.out.println (e.getMessage ());
        }
    }

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result<String> upload( MultipartFile file ){
        log.info ("文件上传:{}",file);

        //获取原始文件名
        String originalFilename = file.getOriginalFilename ();
        String suffix = originalFilename.substring (originalFilename.lastIndexOf ('.'));
        //使用UUID生成文件名
        String fileName = UUID.randomUUID () + suffix;

        //判断存储目录是否存在
        File dir = new File (REGGIE_FILEPATH);
        if(!dir.exists ()){
            //目录不存在，则创建目录
            dir.mkdir ();
        }
        try {
            file.transferTo (new File (REGGIE_FILEPATH + fileName));
        } catch (IOException e) {
            e.printStackTrace ();
        }
        return Result.success (fileName);
    }
}
